package com.dailyblue.java.spring.jwt.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dailyblue.java.spring.jwt.bean.Emp;
import com.dailyblue.java.spring.jwt.config.JwtConfig;
import com.dailyblue.java.spring.jwt.exception.PasswordErrorException;
import com.dailyblue.java.spring.jwt.exception.UsernameNotFoundException;
import com.dailyblue.java.spring.jwt.service.EmpService;
import com.dailyblue.java.spring.jwt.util.ResultCode;
import com.dailyblue.java.spring.jwt.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private EmpService empService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("用户开始登陆");

        // 1. 接收用户输入过来的账号和密码
        String name = request.getParameter("ecode");
        String pass = request.getParameter("epass");
        log.info("接收了账号：{}，密码：{}", name, pass);
        // 2. 验证账号是否存在
        QueryWrapper<Emp> wrapper = new QueryWrapper<>();
        wrapper.eq("ecode", name);
        Emp emp = empService.getOne(wrapper);
        log.info("账号验证后为：{}", emp);
        // 3. 继续下一步
        if (emp == null) {
            log.info("账号不存在");
            // 账号不存在
            throw new UsernameNotFoundException("账号不存在");
        }
        // 4. 比较密码是否正确
        if (!pass.equals(emp.getEpass())) {
            throw new PasswordErrorException("密码错误");
        }
        // 5. 这时候账号密码正确，生成jwt字符串
        String token = JwtConfig.getJwtToken(emp);
        log.info("生成的token:{}", token);
        // 6. 保存这个token字符串到redis
        HashOperations hash = stringRedisTemplate.opsForHash();
        hash.put("token", emp.getId() + "", token);
        stringRedisTemplate.expire("token", 24, TimeUnit.HOURS);
        // 7. 给客户端返回这个token
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(JSONArray.toJSONString(ResultTool.success(token)));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
